import java.util.Scanner;

/**
 * @author gao
 * @date 2025/7/23 18:25
 */

public class Solution {
    public int maxProfit(int k, int[] prices) {
        int n = prices.length, INF = 0x3f3f3f3f;
        // 如果k大于等于n/2，则相当于可以进行无限次交易
        k = Math.min(k, n / 2);

        int[][] f = new int[n][k + 1];
        int[][] g = new int[n][k + 1];
        for (int i = 0; i <= k; i++) {
            f[0][i] = g[0][i] = -INF;
        }
        f[0][0] = -prices[0];
        g[0][0] = 0;
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= k; j++) {
                // f[i][j]表示第i天持有股票的最大收益，g[i][j]表示第i天不持有股票的最大收益
                f[i][j] = Math.max(f[i - 1][j], g[i - 1][j] - prices[i]);
                // g[i][j]表示第i天不持有股票的最大收益，如果第i天不持有股票，那么第i-1天也不持有股票，或者第i天卖出股票
                g[i][j] = g[i - 1][j];
                if (j >= 1) {
                    g[i][j] = Math.max(g[i][j], f[i - 1][j - 1] + prices[i]);
                }
            }
        }
        int ret = 0;
        for (int i = 0; i <= k; i++) {
            // 遍历g数组，找到最大值
            ret = Math.max(ret, g[n - 1][i]);
        }
        return ret;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int k = in.nextInt();
            int n = in.nextInt();
            int[] prices = new int[n];
            for (int i = 0; i < prices.length; i++) {
                prices[i] = in.nextInt();
            }
            Solution solution = new Solution();
            System.out.println(solution.maxProfit(k, prices));
        }
    }
}